package com.android.exchangeapp

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.RadioGroup.OnCheckedChangeListener
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.android.exchangeapp.modle.SupportCurrency

/**
 * Created by Matt on 2023/10/31.
 **/
class SupportListAdapter(
    val list: List<SupportCurrency>,
    val listener: (item: SupportCurrency) -> Unit
) :
    RecyclerView.Adapter<SupportListAdapter.ItemViewHolder>() {

    private val mOnClickListener = View.OnClickListener {
        val position = it.tag as Int
        if (position != mCheckPosition) {
            if (mCheckPosition != -1) {
                notifyItemChanged(mCheckPosition)
            }
            mCheckPosition = position
            notifyItemChanged(mCheckPosition)
            it.post {
                listener.invoke(list[mCheckPosition])
            }
        }
    }

    private val mCheckChangeListener = CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
        if (isChecked) {
            val position = buttonView.tag as Int
            listener.invoke(list[position])
        }
    }

    private var mCheckPosition = -1

    fun setCheckPosition(position: Int) {
        mCheckPosition = position
    }

    class ItemViewHolder(itemView: View) : ViewHolder(itemView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return ItemViewHolder(
            inflater.inflate(R.layout.support_list_item, parent, false)
        )
    }

    override fun getItemCount(): Int = list.size

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val textView = holder.itemView.findViewById<TextView>(R.id.item)
        val item = list[position]
        textView.text = "${item.currency} - ${item.key}"
        holder.itemView.tag = holder.adapterPosition
        holder.itemView.setOnClickListener(mOnClickListener)
        val checkBox = holder.itemView.findViewById<CheckBox>(R.id.checkbox)
        checkBox.tag = holder.adapterPosition
        checkBox.isChecked = mCheckPosition == holder.adapterPosition
        checkBox.setOnCheckedChangeListener(mCheckChangeListener)
    }
}